<template>
  <div>
      <!-- 头部面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>

        <!-- 卡片综合区 -->
        <el-card class="box-card">
          <!-- element栅格布局 -->
          <!-- 头部搜索 -->
          <el-row :gutter="20">
            <el-col :span="7">
              <el-input @clear="fun_clear_keyword" clearable v-model="seach_keyword" type="text" placeholder="请输入内容">
                <el-button @click="fun_seach_user" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-col>
            <el-col :span="10" class="th_02_col">
              <el-button @click="fun_add_user" type="primary">添加用户</el-button>
            </el-col>
          </el-row>
          <!-- 用户列表 -->
          <el-table
            :data="users_table_data"
            stripe
            border
            fit
            style="width: 100%; margin-top: 20px">
            <el-table-column
              prop="username"
              label="姓名">
            </el-table-column>
            <el-table-column
              prop="email"
              label="邮箱">
            </el-table-column>
            <el-table-column
              prop="role_name"
              label="角色">
            </el-table-column>
            <el-table-column
              prop="mobile"
              label="电话">
            </el-table-column>
            <el-table-column label="状态" width="180">
              <template slot-scope="scope" >
                <el-switch @change="fun_state_change(scope.row)" v-model="scope.row.mg_state">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="Eidt_userinfor(scope.row)" type="primary" icon="el-icon-edit"></el-button>
                <el-button @click="del_user(scope.row)" type="danger" icon="el-icon-delete"></el-button>
                <el-button @click="show_set_user_role_onfun(scope.row)" type="info" icon="el-icon-setting"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 列表分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="get_udata_infor.pagenum"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="get_udata_infor.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </el-card>

        <!-- 添加用户的弹出框 -->
        <el-dialog
          title="添加用户"
          :visible.sync="is_show_add_user_box"
          width="50%">
          <!-- 表单主体 -->
          <el-form
            label-width="70px"
            :model="add_form_data"
            :rules="addus_form_rules"
            class="el_form"
            ref="add_user_form">
            <el-form-item prop="username" label="用户名">
              <el-input
                v-model="add_form_data.username"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
              <el-input
                v-model="add_form_data.password"
              ></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input
                v-model="add_form_data.email"
              ></el-input>
            </el-form-item>
            <el-form-item prop="mobile" label="手机">
              <el-input
                v-model="add_form_data.mobile"
              ></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="is_show_add_user_box = false">取 消</el-button>
            <el-button type="primary" @click="add_sure_btn_fun">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 修改用户信息的弹出框 -->
        <el-dialog
          title="修改用户"
          :visible.sync="is_show_Eidt_userinfor_box"
          width="50%">
          <!-- 表单主体 -->
          <el-form
            label-width="70px"
            :model="Eidt_form_data"
            :rules="Eidtus_form_rules"
            class="el_form"
            ref="Eidt_user_form">
            <el-form-item label="用户名">
              <el-input
                v-model="Eidt_user_username"
              ></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input
                v-model="Eidt_form_data.email"
              ></el-input>
            </el-form-item>
            <el-form-item prop="mobile" label="手机">
              <el-input
                v-model="Eidt_form_data.mobile"
              ></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="is_show_add_user_box = false">取 消</el-button>
            <el-button type="primary" @click="Eidt_sure_btn_fun">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 配置用户角色的弹出框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="is_show_set_user_role_box"
          width="50%">
          <template>
            <p>用户名: {{set_role_userinfor.username}}</p>
            <p>当前角色: {{set_role_userinfor.role_name}}</p>
            <el-select v-model="current_sel_value" placeholder="请选择">
              <el-option
                v-for="item in role_lists"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
          <span slot="footer" class="dialog-footer">
            <el-button @click="is_show_set_user_role_box = false">取 消</el-button>
            <el-button type="primary" @click="sure_set_user_role_onfun">确 定</el-button>
          </span>
        </el-dialog>
  
  </div>
</template>

<script>
var a;
export default {
  name: 'Users',
  data () {
    // 邮箱验证函数
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value)) {
        // 验证通过
        return cb();
      }else {
        cb(new Error('邮箱不合法'));
      }
    }
    // 手机号码验证函数
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regEmail = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if(regEmail.test(value)) {
        // 验证通过
        return cb();
      }else {
        return cb(new Error('手机号不合法'));
      }
    }
    return {
      role_lists:[],
      current_sel_value:'',
      set_role_user_id: '',
      get_udata_infor: {
        query:'',
        pagenum: 1,
        pagesize: 2
      },
      users_table_data: [],
      total: 0,
      seach_keyword:'',
      is_show_add_user_box: false,
      is_show_Eidt_userinfor_box: false,
      is_show_set_user_role_box: false,
      // 添加用户的表单数据
      add_form_data:{
        username:'',
        password: '',
        email:'',
        mobile:''
      },
      // 修改用户资料的表单数据
      Eidt_form_data:{
        email:'',
        mobile:'',
        rold_id: ''
      },
      Eidt_user_id: '',
      Eidt_user_username: '',
      // 添加用户的表单格式校验规则
      addus_form_rules:{
        username:[
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 9, message: "长度在3-9位", trigger: "blur" },
        ],
        password:[
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, max: 16, message: "长度在4-16位", trigger: "blur" },
        ],
        email:[
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile:[
          { required: true, message: "请输入手机号码", trigger: "blur" },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户资料表单的验证规则
      Eidtus_form_rules:{
      },
      set_role_userinfor:{}
    }
  },
  methods: {
    // 每页显示大小发生变化
    handleSizeChange(new_pagesize) {
      this.get_udata_infor.pagesize = new_pagesize;
      this.get_table_users_data();
    },
    // 当前页码发生变化
    handleCurrentChange(new_pagenum) {
      this.get_udata_infor.pagenum = new_pagenum;
      this.get_table_users_data();
    },
    // 获取用户列表数据的函数
    get_table_users_data() {
      this.$axios.get('/users', {
        params: this.get_udata_infor
      }).then((res_data) => {
        this.users_table_data = res_data.data.data.users;
        this.total = res_data.data.data.total;
      });
    },
    // 修改用户状态
    async fun_state_change(user_data) {
      const {data:res_data} = await this.$axios.put(`users/${user_data.id}/state/${user_data.mg_state}`);
      if(res_data.meta.status != 200) {
        user_data.mg_state = !user_data.mg_state;
        return this.$Message.error("状态修改错误!");
      }else {
        return this.$Message.success("修改状态成功!");
      }
    },
    // 添加用户请求函数
    async add_user_req() {
      const {data: res_data} = await this.$axios.post('users', this.add_form_data);
      console.log(res_data);
      if(res_data.meta.status != 201) return this.$Message.error('添加失败');
      return this.$Message.success('添加成功');
    },
    // 删除用户的函数
    async del_user_fun(user_data) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res_data} = await this.$axios.delete(`users/${user_data.id}`);
          if(res_data.meta.status != 200) {
            return this.$Message.error('删除失败');
          }
          // 成功后在从新获取用户列表
          this.get_table_users_data();
          return this.$Message.success('删除成功');
        }).catch(() => {
          this.$Message.info('已取消删除');
        });
    },
    // 根据id查询用户信息
    async fun_get_userinforByid(id) {
      const {data: res_data} = await this.$axios.put(`users/${id}`);
      return res_data.data;
      
    },
    // 通过关键字搜索用户
    fun_seach_user() {
      this.get_udata_infor.query = this.seach_keyword;
      this.get_table_users_data();
    },
    // 清空输入框重新获取用户数据
    fun_clear_keyword() {
      this.get_udata_infor.query = '';
      this.get_table_users_data();
    },
    // 添加用户函数
    fun_add_user() {
      this.is_show_add_user_box = true;
    },
    // 在条件用户弹窗里点击确定btn
    add_sure_btn_fun() {
      // elemente ui 的问题 百度找解决方法
      // this.$nextTick(()  => {
      //   console.log(this.$refs.addus_form_rules)
      // })
      this.is_show_add_user_box = false;
      this.add_user_req();
      // 添加好用户后重新获取用户列表
      this.get_table_users_data();
    },
    // 删除用户
    del_user(user_data) {
      this.del_user_fun(user_data);
    },
    // 修改用户资料
    async Eidt_userinfor(user_data) {
      this.is_show_Eidt_userinfor_box = true;
      const userinfor = await this.fun_get_userinforByid(user_data.id);
      this.Eidt_user_username = userinfor.username;
      this.Eidt_user_id = userinfor.id;
      this.Eidt_form_data.rold_id = userinfor.rold_id;
    },
    // 确定修改按钮请求
    async Eidt_sure_btn_fun() {
      this.is_show_Eidt_userinfor_box = false;
      const {data: res_data} = await this.$axios.put(`users/${this.Eidt_user_id}`, this.Eidt_form_data);
      if(res_data.meta.status != 200) {
        this.$refs.Eidt_user_form.resetFields();
        return this.$Message.error('修改失败', res_data.meta.msg);
      }
      this.$refs.Eidt_user_form.resetFields();
      this.get_table_users_data();
      return this.$Message.success('修改成功');
    },
    // 显示户配置角色弹框
    async show_set_user_role_onfun(user_data) {
      this.set_role_userinfor = user_data;
      this.set_role_user_id = user_data.id;
      this.is_show_set_user_role_box = true;
      // 获取全部角色列表
      const {data: res_data} = await this.$axios.get('roles')
      if(res_data.meta.status != 200) return this.$Message.error('获取权限列表失败!'); 
      this.role_lists = res_data.data;
      return this.$Message.success('获取权限列表成功');
    },
    // 确定给用户修改角色
    async sure_set_user_role_onfun() {
      this.is_show_set_user_role_box = false;
      const {data: res_data} = await this.$axios.put(`users/${this.set_role_user_id}/role`, {
        rid:this.current_sel_value
      });
      if(res_data.meta.status != 200) return this.$Message.error('修改失败!');
      this.get_table_users_data();
      return this.$Message.success('修改成功');
    }
  },
  mounted() {
    // 获取用户列表数据的函数的调用
    this.get_table_users_data();
  }
}
</script>

<style>
  .box-card {
    margin-top: 35px;
  }
  .th_02_col {
    display: flex;
    justify-content: start;
  }
  .el-pagination {
    margin-top: 10px;
  }
  .el-select {
    margin-top: 10px;
  } 
</style>